# coding=utf-8 
'''
Created on 2018年1月13日

@author: heguofeng

should change in filefolder.py 2018.3.27 
'''

import os
from _stat import S_ISDIR, S_ISREG
import datetime
from tkinter.messagebox import askyesnocancel
from tkinter.ttk import Frame, Label, Entry, Button, Treeview, Scrollbar,\
    Combobox
from tkinter import StringVar, PhotoImage, Menu
from tkinter.constants import VERTICAL,W,E,N,S
from tkinter.filedialog import askdirectory
import hashlib
import struct
import unittest
import logging
import math
import time

from windbase import Tools

NODE_TYPE_FILE = 1
NODE_TYPE_FOLDER = 2
NODE_TYPE_UP = 3
NODE_TYPE_DOWN = 4
NODE_TYPE_IMAGE = {NODE_TYPE_FILE:"image/file.gif", NODE_TYPE_FOLDER:"image/folder.gif"}
NODE_TYPE_STRING = {NODE_TYPE_FILE:"File", NODE_TYPE_FOLDER:"Folder"}
DATE_FILTER = {"All":(0, 10000), "in 1 week":(0, 7), 'in 1 month':(7, 30), "in 3 month":(30, 90), 'in 1 year':(90, 365), '1 year earlier':(365, 10000)}
DATE_FILTER_TUPLE = ("All", "in 1 week", 'in 1 month', "in 3 month", 'in 1 year', '1 year earlier')
SIZE_FILTER = {"All":(0, 100000000000), "< 1 KB":(0, 1000), '<1 MB':(1000, 1000000), "<10 MB":(1000000, 10000000), '>10 MB':(10000000, 100000000000)}
SIZE_FILTER_TUPLE = ("All", "< 1 KB", '<1 MB', "<10 MB", '>10 MB')
FILE_STATUS={"unknown":128,"new":1,"old":2,"same":4}

       

class FolderWidgets(Frame):
    '''
    widgets has directory label,directory entry,open file dialog button and directory view
    also has popupmenu 
    select event 
    '''

    def __init__(self, master=None, show_full_path=False, folder_label="folder"):
        super().__init__(master)
        self.folderPath = StringVar()
        self.folderInfo = None
        self._load_icon()  # must left in memory
        self.showFullPath = show_full_path
        self.folderLabel = folder_label
        self.createWidgets()
        self.dirTreeview.bind("<<TreeviewSelect>>", self.on_tree_select)
        self.dirTreeview.bind("<Button-3>", self.popupMenu)
        self.dirEntry.bind("<Button-3>", self.popupCopyPasteMenu)
        self.sizeFilterCombobox.bind("<<ComboboxSelected>>", self.filterShow)
        self.dateFilterCombobox.bind("<<ComboboxSelected>>", self.filterShow)
        self.iidNodeInfoDict = {}  # {iid:nodeinfo}
        self.detachIids = {}  # {selfiid:parentiid)
        self.sortDict = {"Name":0, "Size":0, "Date":0, "Path":0, "#0":0}
        self.valueField = {"Path":0, "Name":1, "Size":2, "Date":3, }
        
    def _load_icon(self):
        self.icon = {}
        self.icon[NODE_TYPE_FOLDER] = PhotoImage(data="iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAALLSURBVDhPLZNLT1NRFIUv8hJEAmrUODAxMQw0jtBIogMTBurIwMCQEBLjD9CJiXHiUGcmOnDq35AgLW1paQttaSpPrQE0EUOAYml735/rtDY56bn7nLX32mvtYzVwYR8aHEMAoRbYih7jNXd/MVfMoW/uaO+6NiF1qIHlBCH8GINvd6E4TH1xCEojhD8/ChMosflVBbC1t5XEIxTEJPeUzXJ0GGRGqC9b1HPtHC5akNRaPqHEbxBCtFTNFsALxEMptXerLns6spr0ElchI1BMa7YX5iy8WYtqoY1afpRG8QEUnlBfe0hl4xGsj8PGuJL9MQxEcGkYu9iLH7Fwol2qbuHnlaykta7vTf2b9d2isaYCK+asDyq+GKgFrzSEk+/Hi3TgFq7A6mO8lQnIT+JsTmKvjuGXpnDKE/hbT5VoiqD8TMofYXmIQ/o2brpTIp5S3yk4KBA6JQJvB9fPwtGmYr+xqzmBMrgHX6lWi+p+Acs1vuXuiFYH4eY4/u5bamtqYUHkUqKc1X9SyVUgmNde8UAi+0strRSRp3lZWFBw9xNBWoIKSOw0xBXTIt4GkU4cAZgbaAKRyE6imcCVjbeU8Qz8+kAjNdiswoxsFNiLt7fciXbiChDGFZ/Rd7KLWqobSzOBn7iOV7wvpZ9TN3bO98C0qAroxeRCVLG5dny1EJo1rVhugFruB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HSL10GT8EFzSeq2wnnl4yTKmocT3r1ZuvxrH/8vovviZv/FYPcva4OdbPOaGJwcr2h2OGTDV+Oq7mPLq2OoFa6ia+rZjUUuMnGOwfr9k6yqHghELfcJghU02MxFXB29HSDiirDjReTxrQnNUsPw02p08/ac6zVZUW7db2p6suTm2i6CULjwyaafLEA/mwHqPLu6CIQX1HiLmtbc/WrrQwpvDBCooBaFnytFn3uVApGRf0vAdNMaDX0lzc2vJ8op+kIYYqKHFo83fQouSOYpu/TXIG7Zt5P+9FUwjocjpyMUOmquSz00OAd1NoCwG0CG0xgA7FyDlyKklfvEvGffheCJI8SAyn/8yQqbros6v0jddiaEsRtAiaEWcMWK9fnKF9nd4Aa+nfyXjjfHjrsPwAaiEKrRAzkWKkjqH75h5UKdSRR2XItCN43Yo0rffWZqG9fUSYhVoieWkOWH+IWi60aU0dreS0P65IUb23Pg+tPA+1/AR4P2dc/t3n4TFr2uglk2ugEuPuxjNg4zHoCaf/3Rr+d6LGWul+ryFGP/0XQ6bPCZfTSi8om+0nKo5lLNpCa/oAAAAASUVORK5CYII=")
#         for t in NODE_TYPE_IMAGE:
#             self.icon[t] = ImageTk.PhotoImage(Image.open(NODE_TYPE_IMAGE[t]).resize((16,16))) #must left in memory
            
    def popupMenu(self, event):
        self.popmenu.post(event.x_root, event.y_root)  
    
    def popupCopyPasteMenu(self,event):
        self.popupCCPMenu.post(event.x_root, event.y_root)
       
    def popupCopy(self):
        self.clipboard_clear()
        self.clipboard_append(string=self.folderPath.get(),type='STRING') 
        
    def popupPaste(self):
        self.folderPath.set(self.clipboard_get(type='STRING'))
       
    def on_tree_select(self, event):
        counts = self._getSelectCount()
        self.statusLabel.config(text="%d files %d Bytes selected! "% (counts[1],counts[2]))            
#         if len(self.dirTreeview.selection()) > 0:
#             nodeinfo = self.iidNodeInfoDict[self.dirTreeview.selection()[0]]
#             if nodeinfo != None:
#                 self.statusLabel.config(text=os.path.join(nodeinfo.path, nodeinfo.name))
                
    def selecteFilesInSameFolder(self):
        files = self.dirTreeview.selection()
        if len(files) == 0:
            return 
        path = self.iidNodeInfoDict[files[0]].path
        for iid in self._getVisibleIid(""):
            if self.iidNodeInfoDict[iid]!=None:
                if self.iidNodeInfoDict[iid].path == path and isinstance(self.iidNodeInfoDict[iid],FileInfo):
                    self.dirTreeview.selection_add(iid)
#         counts = self._getSelectCount()
#         self.statusLabel.config(text="%d files %d Bytes selected! "% (counts[1],counts[2]))            
        pass
    
    def removeSelected(self):
        self.dirTreeview.selection_remove(self.dirTreeview.selection())
        return 
    
    def _getSelectCount(self):
        files = self.dirTreeview.selection()   
        tempfolder =  FolderInfo("")
        for f in files:
            tempfile = self.iidNodeInfoDict[f]
            if isinstance(tempfile,FileInfo):
                tempfolder.add("",os.path.join(tempfile.path,tempfile.name),tempfile)
        
        return tempfolder.count()

            
    def createWidgets(self):

        self.dirLabel = Label(self, compound="left" , anchor='w',text=self.folderLabel, \
                              image=self.icon[NODE_TYPE_FOLDER])

        self.dirEntry = Entry(self, width=40, textvariable=self.folderPath)
        self.dirButton = Button(self, text="...", command=self.dirselect)

        self.dirTreeview = Treeview(self, columns=("Path", "Name", "Size", "Date"), \
                                displaycolumns=['Path', 'Name', 'Size', 'Date'], \
                                height=16, show='tree headings')
        self.dirTreeview.heading('#0', command=self.sortClear)
        self.dirTreeview.heading('Path', text="路径", command=lambda : self.sort("Path"))
        self.dirTreeview.heading('Name', text="文件名", command=lambda : self.sort("Name"))
        self.dirTreeview.heading('Size', text="大小", command=lambda : self.sort("Size"))
        self.dirTreeview.heading('Date', text="修改日期", command=lambda : self.sort("Date"))
        self.dirTreeview.column('Path', width=260)
        self.dirTreeview.column('Date', width=80)
        self.dirTreeview.column('Size', width=60)
        self.dirTreeview.column('Name', width=80)
        self.dirTreeview.column('#0', width=60)
        self.dirScrollbar = Scrollbar(self, orient=VERTICAL)

        self.dirLabel.grid(row=0, column=0, sticky= W)
        self.dirEntry.grid(row=0, column=1, columnspan=7, sticky=E + W)
        self.dirButton.grid(row=0, column=7, sticky=E + W)
        self.dirTreeview.grid(row=1, column=0, rowspan=16, columnspan=10, sticky=W + E + N + S)
        self.dirScrollbar.grid(row=1, column=9, rowspan=16, sticky=N + S + E)
        
        self.dirLabel.rowconfigure(0, weight=1)
        self.dirLabel.rowconfigure(0, weight=1)
        
        self.dirScrollbar.configure(command=self.dirTreeview.yview)
        self.dirTreeview.configure(yscrollcommand=self.dirScrollbar.set)
        
        self.sizeFilterLabel = Label(self, text="文件过滤：大小")
        self.sizeFilterLabel.grid(row=17, column=0)
        self.sizeFilterCombobox = Combobox(self , \
                                             values=SIZE_FILTER_TUPLE, \
                                             width=8)
        self.sizeFilterCombobox.grid(row=17, column=1)
        self.sizeFilterCombobox.set("All")
        self.dateFilterLabel = Label(self , text="日期:")
        self.dateFilterLabel.grid(row=17, column=2)
        self.dateFilterCombobox = Combobox(self, \
                                             values=DATE_FILTER_TUPLE, \
                                             width=12)
        self.dateFilterCombobox.grid(row=17, column=3)
        self.dateFilterCombobox.set("All")
        
        self.statusLabel = Label(self, text="", anchor='w',wraplength=500)
        self.statusLabel.grid(row=18, column=0, columnspan=10, sticky=W + E)

        self.popmenu = Menu(self, tearoff=0)
        self.popmenu.add_command(label="删除所选", command=self.deleteFiles)
        self.popmenu.add_command(label="资源管理器打开", command=self.openExplorer)
        self.popmenu.add_command(label="复制目录到剪贴板", command=self.copy2Clipboard)
        
        self.popmenu.add_separator()
        self.popmenu.add_command(label="选择该目录所有文件", command=self.selecteFilesInSameFolder)
        self.popmenu.add_command(label="取消选择", command=self.removeSelected)
        
        self.popupCCPMenu = Menu(self, tearoff=0)
        self.popupCCPMenu.add_command(label="copy", command=self.popupCopy)
        self.popupCCPMenu.add_command(label="paste", command=self.popupPaste)

         
        if not self.showFullPath:
            self.dirTreeview.config(displaycolumns=['Name', 'Size', 'Date'])
    
    def _getVisibleIid(self, parentiid):
        iids = []
        for i in self.dirTreeview.get_children(parentiid):
            iids.append(i)
            iids.extend(self._getVisibleIid(i))
        return iids
    
    def _clearSort(self):
        for item in self.sortDict:
            self.sortDict[item] = 0
            self.dirTreeview.heading(item, image="")        
            
    def sortClear(self):
        self._clearSort()
        self.refreshTreeview()
 
    def sort(self, bytype):
        self.sortDict[bytype] = (self.sortDict[bytype] + 1) % 2 
        self.dirTreeview.heading(bytype, image=self.icon[self.sortDict[bytype] + 3])
        iidsall = self._getVisibleIid("")
        iids = filter(lambda x:isinstance(self.iidNodeInfoDict[x], FileInfo), iidsall)
        if bytype != "Size":
            iidvalues = list(map(lambda x:(x, self.dirTreeview.item(x, "values")[self.valueField[bytype]]), iids))
        else:
            iidvalues = list(map(lambda x:(x, int(self.dirTreeview.item(x, "values")[self.valueField[bytype]])), iids))
        iidvalues.sort(key=lambda i:i[1], reverse=1 - self.sortDict[bytype])
        for i in range(0, len(iidvalues)):
            self.dirTreeview.move(iidvalues[i][0], "", 0)
        
    def _get1stSelectionPath(self):
        path=""
        files = self.dirTreeview.selection()
        if len(files) > 0:
            path = self.iidNodeInfoDict[files[0]].path
            path = path.replace("/","\\")
            # print(path)
        return path
              
                            
    def openExplorer(self):
        os.system("explorer.exe %s" % self._get1stSelectionPath()) 

    
    def copy2Clipboard(self):
#         w.OpenClipboard()  
#         w.EmptyClipboard()  
#         w.SetClipboardData(win32con.CF_TEXT, self._get1stSelectionPath())  
#         w.CloseClipboard()       
        self.clipboard_clear()
        self.clipboard_append(string=self._get1stSelectionPath(),type='STRING')        

    def deleteFiles(self, files=()):
        if files == ():
            files = self.dirTreeview.selection()   
        message="共%d个文件：\n"%len(files)
        for f in files:
            fileinfo = self.iidNodeInfoDict[f]
            message+=os.path.join(fileinfo.path,fileinfo.name)+"\n"
        if askyesnocancel("真的要删除这些文件吗？",message[0:1000]):
            for f in files:
                self.iidNodeInfoDict[f].remove()
                self.dirTreeview.delete(f)
        return 
    

    def copyFiles(self, files=[]):
        print("copy")
        pass
        
    def dirselect(self):
        # print(self.folderPath.get())
        selectedDir = askdirectory(initialdir=self.folderPath.get())
        # print(selectedDir)
        if selectedDir != "":
            self.folderPath.set(selectedDir)
            self.folderInfo = FolderInfo(selectedDir)
            self.refreshTreeview()
        return
    
    def refreshTreeview(self, folderInfo=None):
        self.clearTreeview()
        if folderInfo != None:
            self.folderInfo = folderInfo
        self.insert_folder("", self.folderInfo)
    
    def clearTreeview(self):
        for i in self.dirTreeview.get_children():
            self.dirTreeview.delete(i)
        self.iidNodeInfoDict.clear()
        self.detachIids.clear()
        self._clearSort()
#         self.sizeFilterCombobox.set("All")
#         self.dateFilterCombobox.set("All")
            
    def insertTreeviewItem(self, treeParent, nodeInfo, showFullPath=False):
        if nodeInfo == None:
            iid = self.dirTreeview.insert(parent=treeParent, index='end', open=True, values=("", "", "", ""))
            self.iidNodeInfoDict[iid] = None
            return iid
        
        if isinstance(nodeInfo, FolderInfo):
            iid = self.dirTreeview.insert(parent=treeParent, index='end', open=True, \
                                values=("", \
                                        "", \
                                        "", \
                                        ""), \
                                image=self.icon[NODE_TYPE_FOLDER], text=nodeInfo.name)
            
        if isinstance(nodeInfo, FileInfo):
#            if fileinfo.status == FILE_STATUS_NEW:
            iid = self.dirTreeview.insert(parent=treeParent, index='end', \
                                 values=(nodeInfo.path, \
                                         nodeInfo.name, \
                                         nodeInfo.size, \
                                         datetime.datetime.fromtimestamp(nodeInfo.mtime).strftime('%Y%m%d %H:%M:%S'), \
                                         ), \
                                image=self.icon[NODE_TYPE_FILE])
        self.iidNodeInfoDict[iid] = nodeInfo
        return iid    
    
    def insert_folder(self, treeParent, folderInfo):  
        if folderInfo == None:
            return
        for node in folderInfo.nodes:
            iid = self.insertTreeviewItem(treeParent, folderInfo.nodes[node])
            if isinstance(folderInfo.nodes[node], FolderInfo):
                self.insert_folder(iid, folderInfo.nodes[node])
  
        pass
    
    def inFilter(self, iid):
        return self._inFilter(iid, self._getFilter())
    
    def _inFilter(self, iid, filter={}):
        '''
        filter = {"size":(0,10000000),"date":（"19000101"，"2099010"),"status":"="}
        return:
        0    not in filter and it is a file
        1    in filter and it is a file
        -1   its not real file,maybe empty maybe folder
        '''
        sizeFilter = filter.get("size", SIZE_FILTER["All"])
        dateFilter = filter.get("date", ("19000101", "20990101"))
        sizeString = self.dirTreeview.item(iid)["values"][self.valueField["Size"]]
        if sizeString != "":
            size = int(sizeString)

            date = self.dirTreeview.item(iid)["values"][self.valueField["Date"]][0:8]
            if size <= sizeFilter[1] and size >= sizeFilter[0] \
                and date >= dateFilter[0] and date <= dateFilter[1]:
                # print(iid,self.dirTreeview.item(iid),filter)
                return 1
            else:
                return 0
        return -1
    
    def filterOut(self, iid):
        self.detachIids[iid] = self.dirTreeview.parent(iid)
        self.dirTreeview.detach(iid)
        pass
    
    def _filterChildren(self, parent, filter):
        iids = {}
        for i in self.dirTreeview.get_children(parent):
            if  self._inFilter(i, filter)==0 :
                iids[i] = parent
            iids.update(self._filterChildren(i, filter))
        return iids
     
    def _checkNoChild(self, parent, grandpa): 
        hasChild = False  #suppose have child    
        for i in self.dirTreeview.get_children(parent):
            hasChild = True
            self._checkNoChild(i, parent)
            if self.detachIids.get(i, None) == None: # if anyone not in detach keep it 
                return
        if hasChild:  # all children  in detach , remove  it 
            self.detachIids[parent] = grandpa
            
    def _getFilter(self):
        sizeFilter = SIZE_FILTER[self.sizeFilterCombobox.get()]
        dateFilter = DATE_FILTER[self.dateFilterCombobox.get()]
        date0 = datetime.datetime.fromtimestamp(datetime.datetime.today().timestamp() - dateFilter[1] * 24 * 60 * 60).strftime("%Y%m%d")
        date1 = datetime.datetime.fromtimestamp(datetime.datetime.today().timestamp() - dateFilter[0] * 24 * 60 * 60).strftime("%Y%m%d")
        return {"size":sizeFilter, "date":(date0, date1)}
            
    def filterShow(self, event=None):
        self._removeFilterShow("")
        filter = self._getFilter()
        self.detachIids = self._filterChildren("", filter)
        for i in self.dirTreeview.get_children(""):
            self._checkNoChild(i, "")
        for iid in self.detachIids:
            self.dirTreeview.detach(iid)
        pass

    def _removeFilterShow(self, parent):
        for iid in self.detachIids:
            self.dirTreeview.move(iid, self.detachIids[iid], 'end')
        self.detachIids.clear()
        pass
           
class Test(unittest.TestCase):


    def setUp(self):
        Tools.set_debug(logging.INFO,"")
        
        pass        


    def tearDown(self):

        pass


#     def testFileInfo(self):
#         f=open("test.txt","wt")
#         f.write("it is a test file")
#         f.close()
#         fileinfo = FileInfo(filepath=".", filename="test.txt", fileinfo=None)
#         print(fileinfo)
#         bindata = fileinfo.dump_info()
#         print(bindata)
#         fileinfo1 = FileInfo(filepath=".",bin_info = bindata)
#         print(fileinfo1) 
#         
#     def testFolderInfo(self):
#  
#         folderinfo = FolderInfo(folder_path=r"C:\Users\heguofeng\workspace\FileManage", folder_name="image")
#         print(folderinfo)
#         bindata = folderinfo.dump_info()
#         print(len(bindata),bindata)
#         folderinfo1 = FolderInfo(folder_path=".",bin_info = bindata)
#         print(folderinfo1)     
    
        
    def testFilter(self):
        folderinfo = FolderInfo(folder_path=r"C:\Users\heguofeng\workspace\FileManage", folder_name="image")
        print(folderinfo)
        filted_info = folderinfo.filter(filter_func=lambda node:True if node.name.startswith("f") else False)
        print(filted_info)
        print(filted_info.dump_info())
        

        
